/*
 * SPDX-FileCopyrightText: 2021~2021 CSSlayer <wengxt@gmail.com>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */
#ifndef _FCITX5_NetIM_NetIM_H_
#define _FCITX5_NetIM_NetIM_H_

#include <fcitx-utils/inputbuffer.h>
#include <fcitx/addonfactory.h>
#include <fcitx/addonmanager.h>
#include <fcitx/inputcontext.h>
#include <fcitx/inputcontextproperty.h>
#include <fcitx/inputmethodengine.h>
#include <fcitx/inputpanel.h>
#include <fcitx/instance.h>
#include <iconv.h>
#include <thread>

class NetIMEngine;

class NetIMState : public fcitx::InputContextProperty {
public:
    NetIMState(NetIMEngine *engine, fcitx::InputContext *ic)
        : engine_(engine), ic_(ic) {}

    void keyEvent(fcitx::KeyEvent &keyEvent);
    void setCode(int code);
    void updateUI();
    void reset() {
        buffer_.clear();
        updateUI();
    }
    char* res[1];
    // const char *candStr1="正在录音，再按右侧‘Ctrl’结束录音";
    // const char *candStr2="按右侧‘Ctrl’录音";
    const char *candStr1="";
    const char *candStr2="";
    const char *preEdit = "_";
    //bool wait_status = false;

private:
    NetIMEngine *engine_;
    fcitx::InputContext *ic_;
    fcitx::InputBuffer buffer_{{fcitx::InputBufferOption::AsciiOnly,
                                fcitx::InputBufferOption::FixedCursor}};
    
};

class NetIMEngine : public fcitx::InputMethodEngineV2 {
public:
    NetIMEngine(fcitx::Instance *instance);

    void activate(const fcitx::InputMethodEntry &entry,
                  fcitx::InputContextEvent &event) override;
    void keyEvent(const fcitx::InputMethodEntry &entry,
                  fcitx::KeyEvent &keyEvent) override;

    void reset(const fcitx::InputMethodEntry &,
               fcitx::InputContextEvent &event) override;

    auto factory() const { return &factory_; }
    auto conv() const { return conv_; }
    auto instance() const { return instance_; }

    static void net_read_loop();
    static NetIMState *net_imstat;
    static fcitx::InputContext *net_ic;
    std::thread *looper;
    bool looper_status = false;

    FCITX_ADDON_DEPENDENCY_LOADER(quickphrase, instance_->addonManager());
    FCITX_ADDON_DEPENDENCY_LOADER(punctuation, instance_->addonManager());

private:
    FCITX_ADDON_DEPENDENCY_LOADER(chttrans, instance_->addonManager());
    FCITX_ADDON_DEPENDENCY_LOADER(fullwidth, instance_->addonManager());

    fcitx::Instance *instance_;
    fcitx::FactoryFor<NetIMState> factory_;
    iconv_t conv_;
};
NetIMState * NetIMEngine::net_imstat = NULL;
fcitx::InputContext * NetIMEngine::net_ic = NULL;

class NetIMEngineFactory : public fcitx::AddonFactory {
    fcitx::AddonInstance *create(fcitx::AddonManager *manager) override {
        FCITX_UNUSED(manager);
        return new NetIMEngine(manager->instance());
    }
};

#endif // _FCITX5_NetIM_NetIM_H_
